/**
 * 
 */
package cn.ad.server.web.init;

import cn.ad.server.persistence.dao.PlatformIndustryDao;
import cn.ad.server.web.spring.service.bomodel.PlatIndustry;
import cn.ad.server.web.spring.service.ehcache.EHCacheHelper;
import cn.ad.server.web.spring.service.ehcache.EhCacheConstants;
import cn.ad.server.domain.ad.Industry;
import cn.ad.server.domain.ad.platform.MapperPlatformIndustry;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 平台行业分类映射加载类
 * @author Wu Chengjun
 */
public class PlatformIndustryMapperLoader implements IAdserverInitialization{
	
	@Autowired
	private PlatformIndustryDao piDao;
	
	@Autowired
	private EHCacheHelper eHCacheHelper;
	
	@Override
	public void init() throws AdserverInitException {
		load();		
	}
	
	/**
	 * 加载数据并写入缓存
	 */
	public void load(){
		Map<PlatIndustry.Key, PlatIndustry> map = loadFromDB();
		writeToEhcache(map);
	}
	
	/**
	 * 从数据库中加载
	 * @return
	 */
	private Map<PlatIndustry.Key, PlatIndustry> loadFromDB(){
		Map<PlatIndustry.Key, PlatIndustry> map = new HashMap<PlatIndustry.Key, PlatIndustry>();
		List<MapperPlatformIndustry> list = piDao.findAll();
		if(list != null && list.size() > 0){
			for(MapperPlatformIndustry mpi : list){
				PlatIndustry.Key key = new PlatIndustry.Key(mpi.getPlatformId(), mpi.getPlatformIndustryId());
				PlatIndustry pi = map.get(key);
				if(pi == null){
					pi = new PlatIndustry();
					map.put(key, pi);
				}
				pi.getIndustrys().add(new Industry(mpi.getIndustryId(), mpi.getParentId(), mpi.getName()));
			}
		}
		return map;
	}
	
	/**
	 * 写入到本地缓存中
	 * @param map
	 */
	private void writeToEhcache(Map<PlatIndustry.Key, PlatIndustry> map){
		eHCacheHelper.clearCache(EhCacheConstants.CACHE_INDUSTRY);
		for(PlatIndustry.Key key : map.keySet()){
			eHCacheHelper.setCache(EhCacheConstants.CACHE_INDUSTRY, key, map.get(key));
		}
	}
}
